<template>
    <div class="userManagement-addAndEdit-com">
        <h2 class="tap">药店端用户管理{{typeName}}</h2>
        <h2 class="title">基本信息</h2>
        <Form
            ref="userBaseInfo"
            :model="userBaseInfo"
            :rules="userBaseInfoRules"
            label-position="left"
            :label-width="80"
            class="user-base-info"
        >
        <Row>
            <i-col :span="item.span" v-for="(item, index) in userBaseInfoObj" v-if="!item.isHide" :key="item.key">
            <FormItem :prop="item.key" :label="item.label" class='marleft'>
                <div class="input-wrapper" @click.stop>
                    <Input
                        v-if="item.type === 'input'"
                        @on-focus="focusNameInput(item)"
                        @on-blur="blurNameInput"
                        v-model="userBaseInfo[item.key]"
                        class="nameInput"
                        :disabled="item.disabled"
                        :placeholder="item.placeholder"
                        :maxlength="item.maxlength"
                    />
                </div>
                <div v-if="item.type === 'inputOrBtn'">
                    <Input
                        v-if="!userBaseInfo.userType"
                        @on-focus="focusNameInput(item)"
                        @on-blur="blurNameInput"
                        v-model="userBaseInfo[item.key]"
                        class="nameInput"
                        :disabled="item.disabled"
                        :placeholder="item.placeholder"
                    />
                <div v-if="userBaseInfo.userType">
                    <span>{{userBaseInfo.name}}</span>
                    <Button v-if='mode=="add"' @click="showYaoshiModal = true">选择药师</Button>
                </div>
            </div>
            <RadioGroup v-if="item.type === 'radio'" v-model="userBaseInfo[item.key]">
                <Radio
                    v-for="(selectItem, index) in item.selections"
                    :key="index"
                    :disabled="item.disabled"
                    :label="(selectItem.value)"
                >{{selectItem.label}}</Radio>
            </RadioGroup>
            <DatePicker
                v-if="item.type === 'datePicker'"
                v-model="userBaseInfo[item.key]"
                type="date"
                clearable
                :disabled="item.disabled"
                :placeholder="item.placeholder"
                :open="openDate"
                @on-open-change="dateOpenChange"
            ></DatePicker>
            </FormItem>
        </i-col>
        </Row>
        </Form>
    <div class="title-wrapper">
        <h2 class="title">药店角色设置</h2>
    </div>
    <div class='shabor'>
        <div class="title-wrapper">
            <Button class='btn' type="primary" @click="handAddStore">
                <i class = "iconfont icon-add" ></i>添加药店
            </Button>
        </div>
        <Form
            ref="storeRoleConfig"
            :model="storeRoleConfigInfoObj"
            :rules="storeRoleConfigInfoRule"
            label-position="right"
            :label-width="90"
            class="store-role-config">
            <div v-for="(item, index) in storeRoleConfigInfoObj.items" v-if="!item.deleted"  :key="item.index">
                <Row gutter="12">
                    <Col class="left-items" span="15">
                        <Row gutter="12">
                            <Col span="12">
                                <FormItem
                                label="所在药店："
                                :prop="'items.' + index + '.storeValue'"
                                :rules="{required: true, message: '请选择药店', trigger: 'change',type:'string'}">
                                <Select
                                    v-model="item.storeValue"
                                    @on-change="($event) => handleChangeHospital($event, item)"
                                    placeholder="请选择药店" clearable>
                                    <Option
                                    :value="item.hospitalId"
                                    :key="item.hospitalId"
                                    v-for="item in hospitalsList"
                                    >{{item.hospitalName}}</Option>
                                </Select>
                                </FormItem>
                            </Col>
                            <Col span="12" v-if="item.roleSelections.length">
                                <FormItem
                                label="角色："
                                :prop="'items.' + index + '.roleValue'"
                                :rules="{required: true, type: 'array', message: '请选择角色', trigger: 'change'}"
                                >
                                    <CheckboxGroup v-model="item.roleValue">
                                        <Checkbox :label="item.roleId" :key="item.id" v-for="item in item.roleSelections">{{item.name}}</Checkbox>
                                    </CheckboxGroup>
                                </FormItem>
                            </Col>
                        </Row>
                    </Col>
                    <Col span="4">
                        <Button class='btn' type="ghost" @click="handleRemoveStore(item, index)">
                            <i class = "iconfont icon-shanchu"></i>删除
                        </Button>
                    </Col>
                </Row>
            </div>
        </Form>
    </div>
    <div class="btn-group">
        <Button style="width:75px;height:35px;" class="btn-left btn" type="primary" :loading="saveBtnLoading" @click="handleSave">
            <Icon class='Icon' type="ios-checkmark" />保存
        </Button>
        <Button style="width:75px;height:35px;" class="btn-right btn" @click="handleBack">
            <i class = "iconfont icon-butongyi"></i>返回
        </Button>
    </div>
    <yaoshiChooseModel v-model="showYaoshiModal" :onOk="handleChooseYaoshi" />
</div>
</template>

<script>
import Utils from "@/utils";
import { DatePicker } from "view-design";
import api from "@/api/commonApi";
import yaoshiChooseModel from "./yaoshiChooseModel";
const userBaseInfoObj = [
    {
        key: "userType",
        type: "radio",
        initialValue: 1,
        selections: [
            { label: "药师", value: 1 },
            { label: "药店工作人员", value: 0 }
        ],
        span: 8,
        label: "用户类型："
    },
    {
        key: "name",
        type: "inputOrBtn",
        span: 8,
        label: "姓名：",
        placeholder: "姓名"
    },
    {
        key: "gender",
        type: "radio",
        selections: [
            { label: "男", value: 1 },
            { label: "女", value: 2 }
        ],
        span: 8,
        // disabled: true,
        label: "性别："
    },
    {
        key: "phone",
        type: "input",
        placeholder: "请输入手机号",
        span: 8,
        label: "手机号：",
        disabled: true,
    },
    {
        key: "birthday",
        type: "datePicker",
        placeholder: "请选择出生年月",
        span: 8,
        label: "出生年月：",
        disabled: true
    },
    {
        key: "email",
        type: "input",
        span: 8,
        label: "邮箱：",
        placeholder: "请输入邮箱",
        maxlength: 50
    },
    {
        key: "loginName",
        type: "input",
        span: 8,
        label: "账号：",
        disabled: true,
        placeholder: "请输入手机号"
    },
    {
        key: "password",
        type: "input",
        span: 8,
        label: "密码",
        disabled: true,
        placeholder: "请输入密码",
        isHide: true,
    }
];
const userBaseInfo = {
    userType: 1,
    name: null,
    gender: 1,
    phone: null,
    birthday: null,
    email: null,
    loginName: null,
    password: null,
};
export default {
    components: {
        yaoshiChooseModel,
        DatePicker
    },
    data() {
        return {
            mode:"add",
            typeName: "新增",
            doctorId: null,
            userBaseInfoObj: this.deepClone(userBaseInfoObj),
            userBaseInfo: this.deepClone(userBaseInfo),
            userBaseInfoRules: {
                phone: [
                    {
                        required: true,
                        message: "请输入正确的手机号",
                        trigger: "change",
                        pattern: Utils.pattern.phone
                    }
                ],
                name: [{ required: true, message: "请输入姓名", trigger: "change" }],
                loginName: [
                    { required: true, message: "请输入正确的手机号", trigger: "change",pattern: Utils.pattern.phone }
                ],
                password: [{ required: true, message: "请输入密码", trigger: "change" }]
            },
            storeRoleConfigInfoObj: {
                items: [
                ]
            },
            storeRoleConfigInfoRule: {},
            doctorsList: [],
            gen: [],
            hospitalsList: [],
            showDoctorList: false,
            openDate: false, // 修复日历disabled状态下仍然可选的bug;
            saveBtnLoading: false,
            showYaoshiModal: false,
        };
    },
    mounted() {
        const that = this;
        if(this.$route.query.id){
            //详情接口
            this.mode="edit"
            this.typeName = '编辑'
            this.getUserBaseInfoObjItemByKey("userType").disabled = true;
            this.storeManagementUserDetail();
        }
        document.addEventListener("click", function(e) {
            if (e.target.className != "nameInput") {
                that.showDoctorList = false;
            }
        });
        this.getMechanismreg();
    },
    methods: {
        isHospitalDisabled(option) {
        const curItem = this.storeRoleConfigInfoObj.items.filter(item => item.storeValue === option.id)[0];
        if ( curItem &&!curItem.deleted ) {
            return true;
        } else {
            return false;
        }
        },
        handleSave() {
        this.$refs["userBaseInfo"].validate(valid => {
            if (valid) {
            console.log(this.$refs["storeRoleConfig"]);
            if (this.storeRoleConfigInfoObj.items.length) {
                let itemList = null;
                for(let i=0; i<this.storeRoleConfigInfoObj.items.length; i++){
                    if(itemList == null){
                        itemList = this.storeRoleConfigInfoObj.items[i].storeValue;
                    }else if(itemList.indexOf(this.storeRoleConfigInfoObj.items[i].storeValue)!=-1){
                        this.$Message.error('药店不能重复!');
                        return;
                    }else{
                        itemList +=","+ this.storeRoleConfigInfoObj.items[i].storeValue;
                    }
                }
                this.$refs["storeRoleConfig"].validate(valid2 => {
                    if (valid2) {
                        this.storeManagementUserCreateOrUpdate();
                    }
                });
            } else {
                this.$Message.error('请添加所在药店');
            }
            }
        });
        },
        handleBack() {
        this.$router.push({
            path: "/index/drugfirmsmanage/usermanagement/index",
            query: this.$route.query
        });
        },
        handAddStore() {
            this.storeRoleConfigInfoObj.items.push({
                storeValue: "",
                roleValue: [],
                roleSelections: []
            });
        },
        handleRemoveStore(item, index) {
            // item.deleted = 1;
            this.storeRoleConfigInfoObj.items.splice(index,1)
            this.$forceUpdate();
            console.log(this.storeRoleConfigInfoObj.items)
        },
        handleChooseYaoshi(item) {
            console.log(item)
            this.doctorId =  item.id;
            this.userBaseInfo.name = item.name;
            this.userBaseInfo.gender = item.gender;
            this.userBaseInfo.phone = item.phone;
            // this.userBaseInfo.birthday = item.birthday;
            this.userBaseInfo.birthday=item.birthday?item.birthday:item.idcard.substr(6,8)
            this.userBaseInfo.loginName = item.phone;
            this.showYaoshiModal = false;
            //医生所在药店与权限
            this.$axios.post(api.storeManagementUserHospitals.replace(/{id}/,this.doctorId),{}).then(res => {
            if (res.data.code !== 1) {
                this.$Message.error(res.data.message);
            } else {
                this.storeRoleConfigInfoObj.items = res.data.object.map((item) => {
                    return {
                        storeValue: item.hospitalId,
                        roleValue: item.userRoles.filter(item => item.checked === true).map(item => item.roleId),
                        roleSelections: item.userRoles.map(item =>{ return { roleId: item.roleId, id: item.id, name: item.roleName }}),
                    }
                });
                console.log(this.storeRoleConfigInfoObj.items)
            }
            })
            .catch(res => {});
        },
        handleChangeHospital(e, item) {
            if (e) {
                this.storeManagementRoleList(item);
            }
            item.roleSelections = [];
            item.roleValue = [];
        },
        focusNameInput(item) {
        if (item.key === "name") {
            this.showDoctorList = true;
        }
        },
        dateOpenChange(e) {
        if (!this.userBaseInfo.userType) {
            this.openDate = e;
        }
        },
        storeManagementUserCreateOrUpdate() {
        let reqApi = '';
        this.mode === 'add' && (reqApi = api.storeManagementUserCreate);
        this.mode === 'edit' && (reqApi = api.storeManagementUserUpdate);

        const reqBody = this.deepClone(this.userBaseInfo);
        if (reqBody.userType) {
            reqBody.doctorId = this.doctorId;
        }
        delete reqBody.userType;
        reqBody.birthday = Utils.getNowDateBySpecialFormat(reqBody.birthday);
        if(this.mode === 'edit'){
            reqBody.password = null;
        }
        console.log(reqBody)
        console.log(this.storeRoleConfigInfoObj)
        reqBody.hospitals = this.storeRoleConfigInfoObj.items.map((item) => {
            this.gen=[]
            let  a = item.roleSelections.map(ite => {
                let genInitRoles = item.roleValue.map(i => {
                    if(ite.roleId==i){
                        let b={}
                        b.roleId=ite.roleId,
                        b.id=ite.id,
                        b.deleted=1,
                        // console.log(b)
                        this.gen.push(b)
                    }
                });
            });
            var name 
            this.hospitalsList.map(i => {
                if(item.storeValue==i.hospitalId){
                    name =  i.hospitalName
                }
            });
            // console.log(name)
            return {
                hospitalId: item.storeValue,
                hospitalName: name,
                deleted: item.deleted ? 1 : 0,
                userRoles: this.gen.map(item2 => {
                    return {
                        roleId: item2.roleId,
                        id: item2.id,
                        // deleted: item.roleValue.indexOf(item2.roleId) > -1 ? 0 : 1
                    }
                }),
            }
        });
        // console.log(reqBody)
        this.mode === 'edit' && (reqBody.id = this.$route.query.id);
        
        this.saveBtnLoading = true;
        this.$axios
            .post(reqApi, reqBody)
            .then(res => {
                if (res.data.code !== 1) {
                    this.$Message.error(res.data.message);
                } else {
                    this.$Message.success('保存成功');
                    this.handleBack();
                }
                this.saveBtnLoading = false;
            })
            .catch(res => {
                this.saveBtnLoading = false;
            });
        },
        storeManagementUserAvailableHospitals() {
        this.$axios.post(api.storeManagementUserAvailableHospitals.replace(/{id}/, this.$route.query.id),{}).then(res => {
            console.log("storeManagementUserAvailableHospitals", res.data.object);
            if (res.data.code !== 1) {
                this.$Message.error(res.data.message);
            } else {
                this.hospitalsList = res.data.object;
            }
            })
            .catch(res => {});
        },
        getMechanismreg() {
        let params = {
            pageNo: 1,
            pageSize: 9999,
            hospitalType: 2
        };
        this.$axios.post(api.mechanismregList, params).then(res => {
            if (res.data.code) {
            this.hospitalsList = res.data.object.records.map(item => {
                return {
                    hospitalId: item.id,
                    hospitalName: item.orgName
                }
            });
            } else {
            this.$Message.error(res.data.message);
            }
        });
        },
        storeManagementUserDetail() {
        let data = {}
        this.$axios.post(api.storeManagementUserDetail.replace(/{id}/, this.$route.query.id),data).then(res => {
            if (res.data.code !== 1) {
                this.$Message.error(res.data.message);
            } else {   
                const {
                name, phone,gender, birthday, email, loginName, password, doctorId
                } = res.data.object;
                console.log(this.userBaseInfo.gender)
                this.userBaseInfo = {
                userType: doctorId ? 1 : 0,
                name,
                phone,
                gender: gender ? parseInt(gender) : 1,
                birthday,
                email,
                loginName,
                password,
                };
                // if(!res.data.object.birthday){
                //     this.userBaseInfo.birthday=res.data.object.idcard.substr(6,8)
                // }
                this.doctorId =doctorId;
                this.storeManagementUserHospitals();
            }
            })
            .catch(res => {});
        },
        // 查询用户所在药店
        storeManagementUserHospitals() {
        this.$axios.post(api.storeManagementUserHospitals.replace(/{id}/,this.$route.query.id),{}).then(res => {
            if (res.data.code !== 1) {
                this.$Message.error(res.data.message);
            } else {
                this.storeRoleConfigInfoObj.items = res.data.object.map((item) => {
                    return {
                        storeValue: item.hospitalId,
                        roleValue: item.userRoles.filter(item => item.checked === true).map(item => item.roleId),
                        roleSelections: item.userRoles.map(item =>{ return { roleId: item.roleId, id: item.id, name: item.roleName }}),
                    }
                });
                console.log(this.storeRoleConfigInfoObj.items)
            }
            })
            .catch(res => {});
        },
        storeManagementRoleList(curItem) {
            const reqObj = {
                "pageNo": 1,
                "pageSize": 99,
            }
        this.$axios
            .post(api.storeManagementRolePage, reqObj)
            .then(res => {
            console.log("storeManagementRoleList", res.data.object.records);
            if (res.data.code !== 1) {
                this.$Message.error(res.data.message);
            } else {
                if (!res.data.object.records.length) {
                    this.$Modal.warning({
                        content: '该药店无角色信息，请选择其他药店',
                        onOk: () => {
                            curItem.storeValue = null;
                        }
                    });
                }
                curItem.roleSelections = res.data.object.records.map(item => {return {roleId: item.id, name: item.name}});
            }
            })
            .catch(res => {});
        },
        deepClone(obj) {
        return JSON.parse(JSON.stringify(obj));
        },
        getUserBaseInfoObjItemByKey(key) {
            return this.userBaseInfoObj.filter(item => item.key === key)[0];
        }
    },
    watch: {
        "userBaseInfo.userType"(n) {
        if (n) {
            this.userBaseInfoObj = this.deepClone(userBaseInfoObj);
        } else {
            // this.getUserBaseInfoObjItemByKey("gender").disabled = false;
            this.getUserBaseInfoObjItemByKey("phone").disabled = false;
            this.getUserBaseInfoObjItemByKey("birthday").disabled = false;
            this.getUserBaseInfoObjItemByKey("loginName").disabled = false;
            this.getUserBaseInfoObjItemByKey("password").disabled = false;
            this.getUserBaseInfoObjItemByKey("password").isHide = false;
            if (this.mode === 'edit') {
            this.getUserBaseInfoObjItemByKey("password").isHide = true;
            }
        }
        this.$refs["userBaseInfo"].resetFields();
        this.userBaseInfo.userType = n;
        },
        "userBaseInfo.name"(n) {},
        "storeRoleConfigInfoObj": {
        handler(newName, oldName) {
            console.log(newName);
        },
        immediate: true,
        deep: true
        }
    }
};
</script>

<style scoped lang="less">
.userManagement-addAndEdit-com {
    width: 100%;
    box-sizing: border-box;
    position: relative;
    background:#fff;
    padding-bottom:30px;
    .marleft{
        margin-left: 30px !important;
    }
    .nameInput{
        width: 95% !important;
    }
    .tap{
        width: 100%;
        height: 50px;
        line-height: 50px;
        text-align: center;
        color: #333;
        font-weight: 550;
        padding-top: 15px;
    }
    .title {
        width: 98%;
        margin:25px auto 0;
        font-size: 20px;
        padding-left: 15px;
        color: #333;
        height: 40px;
        line-height: 40px;
        background: #ebedf8;
        
    }
    .user-base-info {
        width: 98%;
        margin:0px auto ;
        padding-top:20px;
        border: 1px solid #f0f0f0;
        box-shadow: 0 4px 3px #ebedf8;
        .input-wrapper {
        position: relative;
        .tableWrapper {
            position: absolute;
            z-index: 10;
            background-color: #fff;
            width: 100%;
            text-align: center;
            max-height: 500px;
            overflow: auto;
            .doctor-item {
            cursor: pointer;
            display: flex;
            border-left: 1px solid #ccc;
            border-right: 1px solid #ccc;
            &:not(last-child) {
                border-bottom: 1px solid #ccc;
            }
            .name,
            .phone {
                flex: 4 1 0;
            }
            .gender {
                flex: 1 1 0;
                border-left: 1px solid #ccc;
                border-right: 1px solid #ccc;
            }
            }
        }
        }
    }
    .shabor{
        width: 98%;
        height:100%;
        margin:0px auto 20px ;
        border: 1px solid #f0f0f0;
        box-shadow: 0 4px 3px #ebedf8;
    }
    .store-role-config {
        padding-top: 20px;
        width: 98%;
        margin:0px auto ;
        
        .left-items {
        padding: 10px 0 0;
        margin-bottom: 20px;
        margin-left: 60px;
        border: 1px solid #ccc;
        border-radius: 5px;
        }
    }
    .title-wrapper {
        .title {
        padding: 0 0 0 20px;
        }
        Button{
        border-radius: 25px;
        margin-top: 20px;
        margin-left: 60px;
        }
    }
    .btn {
            margin: 0 10px;
            .iconfont{
                font-size:14px !important;
                margin-right:5px !important;
            }
            .Icon{
                margin-right: 5px !important;
            }
        }
    .btn-group {
        text-align: center;
    }
}
</style>